<template>
  <div class="profile-page">
    <div class="page-header">
      <h1>个人信息</h1>
    </div>
    
    <el-card class="profile-card">
      <el-form 
        :model="userInfo" 
        :rules="rules" 
        ref="formRef" 
        label-width="120px"
        v-loading="loading"
      >
        <el-form-item label="用户ID">
          <el-input v-model="userInfo.id" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="登录名">
          <el-input v-model="userInfo.username" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userInfo.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        
        <el-form-item label="角色">
          <el-tag 
            v-for="role in userInfo.roles" 
            :key="role.id" 
            class="role-tag"
            :type="getRoleTagType(role.name)"
          >
            {{ getRoleDisplayName(role.name) }}
          </el-tag>
        </el-form-item>
        
        <el-form-item label="所属部门">
          <el-input 
            v-model="userInfo.departmentName" 
            disabled
            placeholder="暂无所属部门"
          ></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="updateProfile" :loading="updating">
            保存修改
          </el-button>
          <el-button @click="goBack">
            返回
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { getUserInfo, updateUser } from '@/api/user';
import { ElMessage } from 'element-plus';

export default {
  name: 'UserProfile',
  setup() {
    const router = useRouter();
    const userStore = useUserStore();
    const formRef = ref(null);
    const loading = ref(false);
    const updating = ref(false);
    
    const userInfo = ref({
      id: '',
      username: '',
      name: '',
      roles: [],
      departmentName: ''
    });
    
    const rules = {
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ]
    };
    
    // 获取用户信息
    const fetchUserInfo = async () => {
      loading.value = true;
      try {
        const data = await getUserInfo(userStore.username);
        userInfo.value = {
          id: data.id,
          username: data.username,
          name: data.name,
          roles: data.roles || [],
          departmentName: data.department ? data.department.name : ''
        };
      } catch (error) {
        console.error('获取用户信息失败:', error);
        ElMessage.error('获取用户信息失败');
      } finally {
        loading.value = false;
      }
    };
    
    // 更新个人信息
    const updateProfile = async () => {
      if (!formRef.value) return;
      
      try {
        await formRef.value.validate();
        updating.value = true;
        
        const updateData = {
          id: userInfo.value.id,
          name: userInfo.value.name
        };
        
        await updateUser(userInfo.value.id, updateData);
        
        // 更新用户store中的姓名
        userStore.name = userInfo.value.name;
        localStorage.setItem('name', userInfo.value.name);
        
        ElMessage.success('个人信息更新成功');
      } catch (error) {
        console.error('更新个人信息失败:', error);
        ElMessage.error('更新个人信息失败');
      } finally {
        updating.value = false;
      }
    };
    
    // 获取角色显示名称
    const getRoleDisplayName = (roleName) => {
      switch (roleName) {
        case 'ROLE_ADMIN': return '管理员';
        case 'ROLE_DEPARTMENT_HEAD': return '部系领导';
        case 'ROLE_RESEARCH_HEAD': return '教研室领导';
        case 'ROLE_TEACHER': return '教师';
        default: return roleName;
      }
    };
    
    // 获取角色标签类型
    const getRoleTagType = (roleName) => {
      switch (roleName) {
        case 'ROLE_ADMIN': return 'danger';
        case 'ROLE_DEPARTMENT_HEAD': return 'warning';
        case 'ROLE_RESEARCH_HEAD': return 'success';
        case 'ROLE_TEACHER': return 'info';
        default: return '';
      }
    };
    
    const goBack = () => {
      router.go(-1);
    };
    
    onMounted(() => {
      fetchUserInfo();
    });
    
    return {
      userInfo,
      rules,
      formRef,
      loading,
      updating,
      updateProfile,
      getRoleDisplayName,
      getRoleTagType,
      goBack
    };
  }
};
</script>

<style scoped>
.profile-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.profile-card {
  max-width: 600px;
  margin: 0 auto;
}

.role-tag {
  margin-right: 8px;
  margin-bottom: 4px;
}

.el-form-item:last-child {
  margin-bottom: 0;
}
</style>